//
//  PositioningViewController.m
//  一点互助
//
//  Created by 张泊秋 on 16/8/19.
//  Copyright © 2016年 zhangboqiu. All rights reserved.
//

#import "PositioningViewController.h"
#import "FTSearchBar.h"
#import <Masonry.h>
#import "URLDefine.h"
#import "ResponseManager.h"
#import "PositionHeaderCollectionReusableView.h"
#import "PositionCollectionViewCell.h"
#import "PositonFirstCollectionReusableView.h"
#import "PositionModel.h"
#import "UserState.h"


@interface PositioningViewController ()<UISearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (strong, nonatomic) FTSearchBar *searchBar;
@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) UICollectionViewFlowLayout *flowLayout;
@property (strong, nonatomic) NSArray *dataSource;
@property (strong, nonatomic) NSMutableArray *hotDataSource;
@property (strong, nonatomic) NSMutableDictionary *sectionNum;

@end

@implementation PositioningViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setAutomaticallyAdjustsScrollViewInsets:YES];
    [self getRequest];
    [self setupBackItem];
    [self addSearchBar];
    UINib *nib1 = [UINib nibWithNibName:@"PositionCollectionViewCell" bundle:nil];
    [self.collectionView registerNib:nib1 forCellWithReuseIdentifier:@"PositionCollectionViewCell"];
    UINib *nib2 = [UINib nibWithNibName:@"PositionHeaderCollectionReusableView" bundle:nil];
    [_collectionView registerNib:nib2 forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PositionHeaderCollectionReusableView"];
    UINib *nib3 = [UINib nibWithNibName:@"PositonFirstCollectionReusableView" bundle:nil];
    [_collectionView registerNib:nib3 forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PositonFirstCollectionReusableView"];
    
}
-(void)addSearchBar{
    [self.view addSubview:self.searchBar];
    [self.view addSubview:self.collectionView];
}
-(void)getRequest{
    __weak typeof(self) myself = self;
    [ResponseManager startGetRequestWithURLString:kCityList parameters:nil completionHandler:^(FBResponse *response) {
        if (response.success) {
//            PLLOG(@"%@",response.resultValue);
            myself.dataSource = [PositionModel modelWithDic:response.resultValue[@"city"]];
            myself.sectionNum = response.resultValue[@"city"];
//            PLLOG(@"%ld",(long)self.sectionNum);
            self.hotDataSource = response.resultValue[@"hot"];
            [myself.collectionView reloadData];
        }
    }];

}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [_searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_top).with.offset(100);
        make.left.equalTo(self.view.mas_left).with.offset(10);
        make.right.equalTo(self.view.mas_right).with.offset(-10);
        make.height.mas_equalTo(44);
    }];
}

-(FTSearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar = [[FTSearchBar alloc]init];
        _searchBar.delegate = self;
        _searchBar.center = CGPointMake(kScreenWidth/2, 100);
        _searchBar.placeholder = @"城市/拼音";
        _searchBar.layer.cornerRadius = 5;
        _searchBar.backgroundColor = [UIColor colorWithRed:0.4247 green:0.4247 blue:0.4247 alpha:0.18];
    }
    return _searchBar;
}
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 140, kScreenWidth, kScreenHeight-self.searchBar.bounds.size.height-180) collectionViewLayout:self.flowLayout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
    }
    return _collectionView;

}
-(UICollectionViewFlowLayout *)flowLayout{
    if (!_flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc]init];
        //设置每一个cell的大小
        _flowLayout.itemSize = CGSizeMake(100, 30);
        //cell的最小水平间距
        _flowLayout.minimumInteritemSpacing = 10;
        //cell的行间距
        _flowLayout.minimumLineSpacing = 10;
        //cell缩进
        _flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        //滚动方向
        _flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        //设置表头的大小 垂直情况下只需设置高度
        _flowLayout.headerReferenceSize = CGSizeMake(0, 40);
        //设置表尾的高度
        _flowLayout.footerReferenceSize = CGSizeMake(0, 0);
        //滑动时表头是否存在显示
        _flowLayout.sectionHeadersPinToVisibleBounds = YES;
    }
    return _flowLayout;
}
#pragma mark - UICollectionViewDelegate -
//选中cell时
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    NSLog(@"点击了第几%ldsection and 第%ld个row",indexPath.section,indexPath.row);
    UserState *user = [[UserState alloc]init];
   if (indexPath.section == 1) {
        user.location = self.hotDataSource[indexPath.row][@"city_name"];
       [self.navigationController popViewControllerAnimated:YES];
   }else if (indexPath.section == 0){
       [self.navigationController popViewControllerAnimated:YES];
   }
   else{
        NSArray *section = self.sectionNum.allKeys;
        NSArray *new = [section sortedArrayUsingSelector:@selector(compare:)];
        NSArray *arr = self.sectionNum[new[indexPath.section-2]];
        user.location = arr[indexPath.row][@"city_name"];
        [self.navigationController popViewControllerAnimated:YES];
    }

}
//上个点击的cell
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"上一次点击的是%ldrow",indexPath.row);
}
#pragma mark - UICollectionViewDataSource -
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    NSArray *citys = self.sectionNum.allKeys;
    return citys.count+2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return self.hotDataSource.count;
    }else{
        NSArray *sectionKeys = self.sectionNum.allKeys;
        NSArray *new = [sectionKeys sortedArrayUsingSelector:@selector(compare:)];
        NSString *key = new[section-2];
        NSArray *arr = self.sectionNum[key];
        return arr.count;
//        return self.dataSource.count;
    }
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //获取重用的cell

    PositionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PositionCollectionViewCell" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        [self updateLabel:cell];
    }else if (indexPath.section == 1 && self.hotDataSource.count != 0){
//        PLLOG(@"%@",self.hotDataSource);
        cell.label.text = self.hotDataSource[indexPath.row][@"city_name"];
    }
    else{
        NSArray *section = self.sectionNum.allKeys;
        NSArray *new = [section sortedArrayUsingSelector:@selector(compare:)];
        NSArray *arr = self.sectionNum[new[indexPath.section-2]];
//        PLLOG(@"%@",arr);
        cell.label.text = arr[indexPath.row][@"city_name"];
    }

    cell.layer.borderColor = [UIColor grayColor].CGColor;
    cell.layer.borderWidth = 1;
    return cell;
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {
        PositonFirstCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PositonFirstCollectionReusableView" forIndexPath:indexPath];
        header.label.text = @"定位城市";
        header.backgroundColor = [UIColor whiteColor];
        return header;
    }else if (indexPath.section == 1){
            PositonFirstCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PositonFirstCollectionReusableView" forIndexPath:indexPath];
        header.label.text = @"热门城市";
        header.backgroundColor = [UIColor whiteColor];
        return header;
    }else{
        PositionHeaderCollectionReusableView *reusable = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PositionHeaderCollectionReusableView" forIndexPath:indexPath];
        NSDictionary *city = self.sectionNum;
        NSArray *citys = city.allKeys;
        //section名
        NSArray *new = [citys sortedArrayUsingSelector:@selector(compare:)];
        NSString *sectionName =new[indexPath.section-2]; //city[[citys objectAtIndex:indexPath.section]];
        //cell名
        reusable.backgroundColor = [UIColor whiteColor];
        reusable.headerWord.text = sectionName;
        
        return reusable;
    }
}
-(NSArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSArray array];
    }
    return _dataSource;
}
-(NSMutableArray *)hotDataSource{
    if (!_hotDataSource) {
        _hotDataSource = [NSMutableArray array];
    }
    return _hotDataSource;
}
-(void)updateLabel:(PositionCollectionViewCell *)cell{
    UserState *user = [[UserState alloc]init];
    cell.label.text = user.location;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
